<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-12 16:30:58
 * @FilePath: \usp-osm-frondend\src\views\productCenter\label\updateLabel.vue
-->
<template>
  <div class="source" v-loading="pageLoading" :element-loading-text="loadingText">
    <div class="newPageTitle">
      <span class="backIcon" @click="closeDrawer"><i class="el-icon-back"></i></span>
      <h1 v-if="type === 'detail'" style="display:inline-block;margin-left:10px">
        详情
      </h1>
      <h1 v-else-if="type === 'edit'" style="display:inline-block;margin-left:10px">
        修改标签
      </h1>
      <h1 v-else style="display:inline-block;margin-left:10px">
        新增标签
      </h1>
    </div>
    <el-form
      :model="editData"
      :rules="rules"
      label-position="left"
      ref="editLabel"
      label-width="170px"
      size="small"
      class="dialogForm"
    >
      <el-form-item prop="labelName" class="formPosition" label="标签名称">
        <el-input
          :disabled="editData.isEnable === '1' || isDetail"
          type="text"
          v-model="editData.labelName"
          @input="editData.labelName=editData.labelName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
          placeholder="标签名称"
          maxlength="5"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item prop="labelType" class="formPosition" label="标签类型">
        <el-select
          :disabled="editData.isEnable === '1' || isDetail"
          v-model="editData.labelType"
          placeholder="请选择"
        >
          <el-option
            v-for="item in lookupItems.LABELTYPE"
            :key="item.id"
            :label="item.dicName"
            :value="item.dicCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="labelDesc" class="formPosition description" label="标签描述">
        <el-input
          :disabled="editData.isEnable === '1' || isDetail"
          type="text"
          v-model="editData.labelDesc"
          placeholder="标签描述"
          @input="editData.labelName=editData.labelName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
          maxlength="100"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="footer">
      <div class="footer-btn">
        <el-button @click="closeDrawer" class="white-btn">取消</el-button>
        <el-button
          :disabled="editData.isEnable === '1' || isDetail"
          @click="saveEdit('editLabel')"
          class="dark-btn"
        >保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getAttributeDetail, updateLabel } from '@/api/label'
import { mapGetters } from 'vuex'
// import LangDsc from '@/components/LangSet'
// import desc from '@/description/desc'
// import { common } from '@/mixins/common'
import { setRouterParams, getRouterParams } from '@/utils/auth'

export default {
  name: 'updateAttribute',
  // mixins: [common],
  components: { },
  data () {
    var specialValidate = (rule, value, callback) => {
      // 特殊字符判断
      // eslint-disable-next-line
      var reg = /^(?=[0-9a-zA-Z\u4e00-\u9fa5\u00C0-\u00FF])[0-9a-zA-Z\s\u4e00-\u9fa5\d_+-./|:;'&%¿¡\*\(\)\u00C0-\u00FF]+$/i
      if (!reg.test(value)) {
        callback(this.$t('specialValidateMore'))
      } else {
        callback()
      }
    }
    return {
      pageLoading: false,
      isUpdateNum: 0,
      isAdd: true,
      orgId: 1,
      loadingText: '加载中...',
      showNameRequire: false,
      // desc: desc,
      dialogEdit: false,
      dialogTitle: '',
      tabsData: [],
      orderInfo: [],
      rules: {
        labelName: [
          {
            required: true,
            message: '标签属性名称不能为空'
          },
          { validator: specialValidate, trigger: 'blur' }
        ],
        labelType: [
          {
            required: true,
            message: '标签属性类型不能为空',
            trigger: 'blur'
          }
        ],
        labelDesc: [
          {
            required: false,
            message: '请输入属性描述',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur'
          }
        ]
      },
      isDetail: false,
      editData: {},
      isSave: false,
      type: ''
    }
  },
  created () {
    this.attributeAction(this.$route.params.id)
  },
  computed: {
    ...mapGetters(['lookupItems'])
  },
  beforeRouteLeave (to, from, next) {
    if (this.isSave) {
      next()
    } else {
      if (this.isUpdateNum > 1) {
        this.$confirm(this.$t('closeDrawerTip'), '', {
          confirmButtonText: '确定',
          cancelButtonText: this.$t('confirmNo')
        }).then(() => {
          next()
        }).catch(() => {
          next(false)
          this.$setMenuActived(this.$route.path)
        })
      } else {
        next()
      }
    }
  },
  methods: {
    // 根据orgId获取语言数据
    getNowOrgLangList () {
      this.isUpdateNum = 0
      /* === 弹窗监听 start ==== */
      this.$watch('editData', function () {
        this.isUpdateNum++
      }, { deep: true })
      /* === 弹窗监听 end ==== */
    },

    saveEdit (formName) {
      // 保存新增修改
      const self = this
      this.$refs[formName].validate(valid => {
        if (valid) {
          // self.editData.labelName = self.editData.attributeName.trim()
          const data = self.editData
          // if (!self.editData.label.trim()) {
          //   self.showNameRequire = true
          //   return false
          // }
          updateLabel(data)
            .then(response => {
              // 调用接口保存新增修改attribute
              const data = response
              if (Number(data.code) === 1) {
                self.$emit('search')
                self.$alert('数据保存成功', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$router.push({ name: 'labelIndex' })
                  }
                })
                this.isSave = true
              } else {
                this.$confirm(this.$t(response.code), {
                  confirmButtonText: '确认',
                  showCancelButton: false
                })
              }
            })
            .catch(error => {
              this.$confirm(error, {
                confirmbuttontext: '确定',
                showcancelbutton: false
              })
            })
        } else {
          return false
        }
      })
    },
    closeDrawer () {
      this.$router.push({ name: 'labelIndex' })
    },
    attributeAction (id) {
      const name = this.$route.name
      this.type = this.$route.params.type
      if (this.type === 'detail') {
        this.isDetail = true
        this.$route.meta.title = '详情'
        this.$route.meta.titlePath = '详情'
      } else if (this.type === 'edit') {
        this.$route.meta.title = '修改属性'
        this.$route.meta.titlePath = '修改属性'
      } else {
        this.$route.meta.title = '新增属性'
        this.$route.meta.titlePath = '新增属性'
      }
      if (id) {
        this.id = id
        this.isAdd = false
        setRouterParams(this.$route)
        this.edit(this.id)
      } else {
        if (name === 'editLabel') {
          this.isAdd = false
          const routeParams = getRouterParams(this.$route)
          this.id = routeParams.id
          this.edit(this.id)
        } else {
          setRouterParams(this.$route)
          this.isAdd = true
          this.initpage()
        }
      }
    },
    edit (id) {
      const self = this
      const model = { id: id }
      this.pageLoading = true
      getAttributeDetail(model)
        .then(response => {
          this.pageLoading = false
          // 编辑Attribute
          const data = response
          if (data) {
            if (Number(data.code) === 1) {
              const obj = data.obj
              self.editData = {
              // 把数据传给子组件
                id: id,
                labelName: obj.labelName,
                labelDesc: obj.labelDesc,
                labelType: obj.labelType,
                isEnable: obj.isEnable
              }
            } else if (Number(data.code) === 0) {
              this.$confirm(data.msg, {
                confirmButtonText: '确认',
                showCancelButton: false
              })
            } else {
              switch (response.code) {
                case 'MDSE_LABEL_001':
                  this.$confirm('该标签已挂载产品，无法修改', {
                    confirmButtonText: '确定',
                    showCancelButton: false
                  })
                  break

                case 'MDSE_LABEL_002':
                  this.$confirm('当前标签名称已经存在，请重新输入', {
                    confirmButtonText: '确定',
                    showCancelButton: false
                  })
                  break
              }
            }
          }
        })
        .catch(_ => {
          this.pageLoading = false
        })
    },
    initpage () {
      // 初始页面值
      this.editData = {
        labelName: '',
        labelDesc: '',
        labelType: ''
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.langBox {
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
  padding: 2px 0px;
  width: 50px;
  float: left;
  margin-left: 10px;
  span {
    display: block;
    line-height: 12px;
  }
  .lang {
    border-bottom: 1px dashed #ccc;
  }
}
.dialogForm {
  .formPosition {
    position: relative;
  }
  .descSty {
    position: absolute;
    top: -152px;
    left: 115px;
  }
}

/deep/ .el-form--label-left .el-form-item__label {
  text-align: right;
  padding-right: 20px;
}
</style>
